package com.lib.dao;

import com.lib.dao.ex.DaoException;
import com.lib.dao.ex.UpdateDaoException;
import com.lib.entity.Book;
import com.lib.entity.Member;
import com.lib.entity.Record;
import com.lib.util.DBUtil;
import com.lib.util.ResultSetUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public class RecordDao {
    public List<Record> getRecordList() throws DaoException {
        List<Record> recordList = null;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        conn = DBUtil.getConnection();
        try {
            ps = conn.prepareStatement("select * from record ");
            rs = ps.executeQuery();
            recordList = ResultSetUtil.toList(rs, Record.class);

            for (Record record: recordList){
                ps = conn.prepareStatement("select * from book,record where book.id = record.bookid and record.bookid = ?");
                ps.setInt(1,record.getBookId());
                rs = ps.executeQuery();
                Book book = ResultSetUtil.toBean(rs, Book.class);
                record.setBook(book);
            }

        } catch (Exception e) {
            throw new DaoException("查找借阅历史失败：数据库异常" + e.getMessage(), e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }
        return recordList;
    }

    public void updateRecordBackDate(String id,String date) throws UpdateDaoException, DaoException {
        Connection conn = null;
        PreparedStatement ps = null;
        conn = DBUtil.getConnection();
        int count = 0;
        try {
            ps = conn.prepareStatement("update record set backDate = ? where id = ?");
            ps.setString(1,date);
            ps.setString(2,id);
            count = ps.executeUpdate();
        }catch (Exception e){
            throw new DaoException("更新借阅历史失败：数据库异常" + e.getMessage(), e);
        }finally {
            DBUtil.close(conn,ps,null);
        }
        if (count != 1){
            throw new UpdateDaoException("数据库异常：更新借阅历史失败");
        }
    }
}
